package com.dankegongyu.lib.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public abstract class DKBaseDialogFragment extends DialogFragment {

    private static final String MARGIN = "margin";
    private static final String WIDTH = "width";
    private static final String HEIGHT = "height";
    private static final String DIM = "dim_amount";
    private static final String BOTTOM = "show_bottom";
    private static final String CANCEL = "out_cancel";
    private static final String ANIM = "anim_style";
    private static final String LAYOUT = "layout_id";
    @LayoutRes
    protected int layoutId;
    private int margin;//左右边距
    private int width;//宽度
    private int height;//高度
    private float dimAmount = 0.5f;//灰度深浅
    private boolean showBottom;//是否底部显示
    private boolean outCancel = true;//是否点击外部取消
    @StyleRes
    private int animStyle;

    public abstract int intLayoutId();

    public abstract void convertView(DKDialogViewHolder holder, DKBaseDialogFragment dialog);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        layoutId = intLayoutId();

        //恢复保存的数据
        if (savedInstanceState != null) {
            margin = savedInstanceState.getInt(MARGIN);
            width = savedInstanceState.getInt(WIDTH);
            height = savedInstanceState.getInt(HEIGHT);
            dimAmount = savedInstanceState.getFloat(DIM);
            showBottom = savedInstanceState.getBoolean(BOTTOM);
            outCancel = savedInstanceState.getBoolean(CANCEL);
            animStyle = savedInstanceState.getInt(ANIM);
            layoutId = savedInstanceState.getInt(LAYOUT);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@SuppressWarnings("NullableProblems") LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(layoutId, container, false);
        convertView(DKDialogViewHolder.create(view), this);
        return view;
    }

    @Override
    public void onStart() {
        try {
            super.onStart();
            initParams();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 屏幕旋转等导致DialogFragment销毁后重建时保存数据
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(MARGIN, margin);
        outState.putInt(WIDTH, width);
        outState.putInt(HEIGHT, height);
        outState.putFloat(DIM, dimAmount);
        outState.putBoolean(BOTTOM, showBottom);
        outState.putBoolean(CANCEL, outCancel);
        outState.putInt(ANIM, animStyle);
        outState.putInt(LAYOUT, layoutId);
    }

    private void initParams() {
        Window window = getDialog().getWindow();
        if (window != null) {
            //设置背景颜色,只有设置了这个属性,宽度才能全屏MATCH_PARENT
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams lp = window.getAttributes();
            //调节灰色背景透明度[0-1]，默认0.5f
            lp.dimAmount = dimAmount;
            //是否在底部显示
            if (showBottom) {
                lp.gravity = Gravity.BOTTOM;
                if (animStyle == 0) {
                    animStyle = R.style.DKDialogDefaultAnimation;
                }
                // 底部弹窗左上角和右上角设置为圆角
                if (getView() != null) {
                    float radius[] = {8.0f, 8.0f, 8.0f, 8.0f, 0f, 0f, 0f, 0f};
                    Drawable drawable = DKDialogUtil.get4SideCornerShape(getContext(), radius, Color.WHITE);
                    getView().setBackground(drawable);
                }
            }

            //设置dialog宽度
            if (width == 0) {
                lp.width = getScreenWidth(getContext()) - 2 * margin;
            } else if (width == -1) {
                lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            } else {
                lp.width = width;
            }

            //设置dialog高度
            if (height == 0) {
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            } else {
                lp.height = height;
            }

            //设置dialog进入、退出的动画
            window.setWindowAnimations(animStyle);
            window.setAttributes(lp);
        }
        setCancelable(outCancel);
    }

    public DKBaseDialogFragment setMargin(int margin) {
        this.margin = margin;
        return this;
    }

    public DKBaseDialogFragment setWidth(int width) {
        this.width = width;
        return this;
    }

    public DKBaseDialogFragment setHeight(int height) {
        this.height = height;
        return this;
    }

    public DKBaseDialogFragment setDimAmount(float dimAmount) {
        this.dimAmount = dimAmount;
        return this;
    }

    public DKBaseDialogFragment setShowBottom(@SuppressWarnings("SameParameterValue") boolean showBottom) {
        this.showBottom = showBottom;
        return this;
    }

    public DKBaseDialogFragment setOutCancel(@SuppressWarnings("SameParameterValue") boolean outCancel) {
        this.outCancel = outCancel;
        return this;
    }

    public DKBaseDialogFragment setAnimStyle(@StyleRes int animStyle) {
        this.animStyle = animStyle;
        return this;
    }

    @SuppressWarnings("UnusedReturnValue")
    public DKBaseDialogFragment show(FragmentManager manager) {
        if (manager == null) {
            return this;
        }
        FragmentTransaction ft = manager.beginTransaction();
        if (this.isAdded()) {
            //ft.remove(this).commit();
            ft.show(this);
        } else {
            ft.add(this, String.valueOf(System.currentTimeMillis()));
        }
        ft.commitAllowingStateLoss();
        return this;
    }

    @Override
    public void dismiss() {
        //super.dismiss();
        dismissAllowingStateLoss();
    }

    public int getScreenWidth(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return displayMetrics.widthPixels;
    }
}
